<template>
  <basic-container>
    <avue-crud :option="option"
               :table-loading="loading"
               :data="data"
               ref="crud"
               v-model="form"
               :defaults.sync="showColumn"
               :permission="permissionList"
               :page.sync="page"
               :before-open="beforeOpen"
               @sortable-change="sortableChange"
               @row-del="rowDel"
               @row-update="rowUpdate"
               @row-save="rowSave"
               @refresh-change="refreshChange"
               @search-change="searchChange"
               @search-reset="searchReset"
               @selection-change="selectionChange"
               @current-change="currentChange"
               @size-change="sizeChange"
               @filter="filterChange"
               @sort-change="sortChange"
               @row-dblclick="handleRowDBLClick"               
               @on-load="onLoad">
     
      <template slot-scope="scope" slot="menuLeft">
        <el-button type="danger"
                   size="small"
                   icon="el-icon-delete"
                   v-if="permission.general_flow_info_batch_delete"
                   @click.stop="handleDelete">删 除
        </el-button>
      </template>
      <template slot-scope="scope" slot="menu">
        <el-button type="text"
                   size="small"
                   icon="el-icon-s-operation"
                   v-if="permission.general_flow_info_delete"
                   @click="openNodeConfigDialog(scope.row)">节点配置
        </el-button>
      </template> 
      <template slot="menuRight">
        <el-button v-if="permission.general_flow_info_download" type="default" @click.stop="exportExcel"  title="下载" icon="el-icon-download" circle size="small"></el-button>
      </template>
    </avue-crud>
    <!-- 
      配置节点对话框
     -->
    <el-dialog title="配置流程节点" width='90%'  
      :close-on-click-modal='false' 
      :visible.sync="nodeConfigDialog"
      @opened="processFlowDialogOpened"
      >
      <general-flow-node-config 
        ref="childDialog"
        :flowInfo="currentRow"
        @handleBatchAdd="handleBatchAdd">
      </general-flow-node-config>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" icon="el-icon-search" size="small" @click="openFlowCharts">流程图</el-button>
        <el-button   icon="el-icon-close"  size="small" @click="nodeConfigDialog = false">关闭</el-button>
      </div>
    </el-dialog>

    <!-- 
      流程图对话框
     -->
    <el-dialog title="流程图" width='80%' @opened="flowChartDialogOpened" :close-on-click-modal='false' :visible.sync="flowCharts">
      <flow-charts ref="flowChart"></flow-charts>
      <div slot="footer" class="dialog-footer">
        <el-button  icon="el-icon-close"  size="small" @click="flowCharts = false">关闭</el-button>
      </div>
    </el-dialog>
  </basic-container>
</template>

<script>
import {generatorCode,exportSysToolTablesExcel,saveSysToolTables,deleteSysToolTables,querySysToolTables,querySysToolTablesListPage,updateSysToolTables,deleteSysToolTablesList} from '@/api/tool/sysToolTablesApi';
import {exportGeneralFlowInfoExcel,saveOrUpdateGeneralFlowInfo,saveOrUpdateGeneralFlowInfoList,saveGeneralFlowInfo,saveGeneralFlowInfoList,deleteGeneralFlowInfo,queryGeneralFlowInfo,queryGeneralFlowInfoListPage,updateGeneralFlowInfo,deleteGeneralFlowInfoList} from '@/api/general/flow/generalFlowInfoApi';
import {mapGetters} from 'vuex';
import { reqCommonMsg } from '@/util/reqCommonMsg';
import {filterFormat} from '@/util/util';
import GeneralFlowNodeConfig from '@/views/general/flow/generalFlowNodeConfig.vue'
import FlowCharts from '@/views/general/flow/generalFlowCharts.vue';

export default {
  components: {
    GeneralFlowNodeConfig,
    FlowCharts
  },
  data() {
    return {

      // 审批树列表
      treeList: [],
      //
      tableList: [],
      // 流程图对话框
      flowCharts: false,

      activeName: '1',
      //如果做流程表单 请将次开关设置为true，否则设置为false
      isFlowFrom: true,

      importDataArea: '',
      nodeConfigDialog: false,
      form: {},
      currentRow: {},
      selectionList: [],
      loading: true, 
      showColumn: [],
      optionTmp: [],
      option: {
        labelPosition: 'right',
        labelSuffix: '：',
        labelWidth: 120,
        dialogTop: '50',
        indexFixed:true, 
        stripe:true,
        calcHeight: 80,
        searchShow: true,
        searchMenuSpan: 6,
        tip: false,
        border: true,
        index: true,
        selection: true,
        addBtn: true,
        viewBtn: true,
        delBtn: false,
        cancelBtn: true,
        emptyBtn: false,
        printBtn:false,
        saveBtn: true,
        filterBtn:true,       
        menuWidth: 220,
        dialogMenuPosition: 'center',
        dialogDirection:'rtl',
        dialogType:'dialog',
        dialogFullscreen:false,
        dialogClickModal:false,
        dialogWidth: '70%',
        highlightCurrentRow:  true,
        searchShow:true,
        sortable: true,
        column: [
          {
            label: '流程ID',
            prop: 'id', 
            type: 'input', 
            search: true,
            searchMmultiple: false,
            searchLabelWidth: 100,
            multiple: false,
            span: 12,
            sortable: false,
            hide: false,
            display: false,
            overHidden: true,
            rules: [{
              required:  false,
              message: '请输入内容',
              trigger: 'blur'
            }],
            dicData:[]
          },
          {
            label: '流程编号',
            prop: 'flowNo', 
            type: 'input', 
            search: true,
            searchMmultiple: false,
            searchLabelWidth: 100,
            multiple: false,
            span: 12,
            sortable: false,
            hide: false,
            overHidden: true,
            rules: [{
              required:  true,
              message: '请输入内容',
              trigger: 'blur'
            }],
            dicData:[]
          },
          
          {
            label: '流程名称',
            prop: 'flowName', 
            type: 'input', 
            search: false,
            searchMmultiple: false,
            searchLabelWidth: 100,
            multiple: false,
            span: 12,
            sortable: false,
            hide: false,
            overHidden: true,
            rules: [{
              required:  true,
              message: '请输入内容',
              trigger: 'blur'
            }],
            dicData:[]
          },
          {
            label: '流程类型',
            prop: 'flowType', 
            type: 'select', 
            search: false,
            searchMmultiple: false,
            searchLabelWidth: 100,
            multiple: false,
            span: 12,
            sortable: false,
            hide: false,
            overHidden: true,
            value: '1',
            rules: [{
              required:  true,
              message: '请输入内容',
              trigger: 'blur'
            }],
            dicData:[
              {
                label:'审批流程',
                value: '1'
              },
              {
                label:'工作流程',
                value: '2'
              }]
          },
          {
            label: '业务名称',
            prop: 'bizType', 
            type: 'input', 
            search: true,
            searchMmultiple: false,
            searchLabelWidth: 100,
            multiple: false,
            span: 12,
            sortable: false,
            hide: false,
            placeholder: '消息提醒类型',
            overHidden: true,
            rules: [{
              required:  true,
              message: '请输入内容',
              trigger: 'blur'
            }],
            dicData:[]
          },
          {
            label: '表单类型',
            prop: 'formType', 
            type: 'select', 
            search: false,
            searchMmultiple: false,
            searchLabelWidth: 100,
            multiple: false,
            span: 12,
            sortable: false,
            hide: false,
            overHidden: true,
            value: '1',
            rules: [{
              required:  true,
              message: '请输入内容',
              trigger: 'blur'
            }],
            dicData:[
              {
                label:'常规表单',
                value: '1'
              },
              {
                label:'动态表单',
                value: '2'
              }
            ]
          },
          {
            label: '表单ID',
            prop: 'formId', 
            type: 'input', 
            search: false,
            searchMmultiple: false,
            searchLabelWidth: 100,
            multiple: false,
            span: 12,
            sortable: false,
            hide: true,
            overHidden: true,
            rules: [{
              required:  false,
              message: '请输入内容',
              trigger: 'blur'
            }],
            dicData:[]
          },
          
          {
            label: '节点状态编号',
            prop: 'nodeStatusNo', 
            type: 'input', 
            search: false,
            searchMmultiple: false,
            searchLabelWidth: 100,
            multiple: false,
            span: 12,
            sortable: false,
            hide: true,
            overHidden: true, 
            rules: [{
              required:  false,
              message: '请输入内容',
              trigger: 'blur'
            }],
            dicData:[]
          },
          {
            label: '阶段状态编号',
            prop: 'nodeStageStatusNo', 
            type: 'input', 
            search: false,
            searchMmultiple: false,
            searchLabelWidth: 100,
            multiple: false,
            span: 12,
            sortable: false,
            hide: true,
            overHidden: true, 
            rules: [{
              required:  false,
              message: '请输入内容',
              trigger: 'blur'
            }],
            dicData:[]
          },
          {
            label: '执行角色类别',
            prop: 'roleType', 
            type: 'select', 
            search: false,
            searchMmultiple: false,
            searchLabelWidth: 100,
            multiple: false,
            span: 12,
            sortable: false,
            hide: true,
            overHidden: true, 
            rules: [{
              required:  false,
              message: '请输入内容',
              trigger: 'blur'
            }],
            dicData:[]
          },
          {
            label: '审批树',
            prop: 'approveTreeNo', 
            type: 'select', 
            search: false,
            searchMmultiple: false,
            searchLabelWidth: 100,
            multiple: false,
            filterable: true,
            span: 12,
            sortable: false,
            hide: true,
            overHidden: true, 
            rules: [{
              required:  false,
              message: '请输入内容',
              trigger: 'blur'
            }],
            dicData:[]
          },
          {
            label: '表单数据表',
            prop: 'tableList', 
            type: 'select', 
            search: false,
            searchMmultiple: false,
            searchLabelWidth: 100,
            multiple: true,
            filterable: true,
            span: 24,
            sortable: false,
            hide: true,
            overHidden: true, 
            rules: [{
              required:  false,
              message: '请输入内容',
              trigger: 'blur'
            }],
            dicData:[]
          }
        ],
         
      },
      data: [],
      // 请求参数区
      page: {
        pageSize: 10,
        currentPage: 1,
        total: 0
      },
      reqParams: {
        singleBody: {},
        listBody: [{}],
        sqlCondition:[],
        orderRule: {},
        currentPage: 1,
        pageSize: 10
      },
      commonData: null,
      conditions: [],
      orderRules: [],
      singleBody: {}
    };
  },
  computed: {
    ...mapGetters(['website','userInfo','orgTree','genOrgTree','permission']),
    permissionList() {
      return {
        addBtn: this.vaildData(this.permission.general_flow_info_add, false),
        viewBtn: this.vaildData(this.permission.general_flow_info_view, false),
        delBtn: this.vaildData(this.permission.general_flow_info_delete, false),
        editBtn: this.vaildData(this.permission.general_flow_info_edit, false),
        printBtn: this.vaildData(this.permission.general_flow_info_print, false),
        searchBtn:this.vaildData(this.permission.general_flow_info_search, false)
      };
    },
    ids() {
      let ids = [];
      this.selectionList.forEach(ele => {
        ids.push({id : ele.id});
      });
      return ids;
    } 
  },
  methods: { 
    /**
     * 打开流程图对话框
     */
    openFlowCharts(){
      this.flowCharts = true;
    },
    /**
     * 流程对话框打开之后
     */
    flowChartDialogOpened(){
      this.$refs.flowChart.getFlowChartData(this.currentRow.id);
    },
    /**
     * 打开配置对话框
     */
    openNodeConfigDialog(row){
      this.nodeConfigDialog = true;
      this.currentRow = row;
    },
    /**
     * 对话框打开后调用子组件的方法加载数据
     */
    processFlowDialogOpened(){
      this.$refs.childDialog.initialConfigData();
    },
    /**
     * 加载列表数据
     */
    onLoad(page) {
      this.loading = true;
      this.reqParams =  {
        singleBody: this.singleBody,
        listBody: [{}],
        sqlCondition: this.conditions,
        orderRule: this.orderRules,
        currentPage: page.currentPage, 
        pageSize: page.pageSize
      }
      this.commonData = reqCommonMsg(this.reqParams)
      queryGeneralFlowInfoListPage(this.commonData).then(res => {
        const data = res.data.body;
        this.page.total = data.total;
        this.data = data.listBody;
        this.loading = false;
        this.selectionClear();
      }, error => {
        this.loading = false; 
      });
    },
    /**
     * 新增一条记录
     */
    rowSave(row, done, loading) {
      this.reqParams.singleBody = row;
      this.commonData = reqCommonMsg(this.reqParams)
      saveGeneralFlowInfo(this.commonData).then(() => {
        done();
        this.singleBody={};
        this.onLoad(this.page);
        this.$message({
          customClass:'zZindex',
          type: 'success',
          message: '操作成功!'
        });
      }, error => {
        //this.$console.log(error);
        loading();
      });         
      //this.$console.log("row = ",row ,loading)
    },
    /**
     * 修改一条记录
     */
    rowUpdate(row, index, done, loading) { 
      //this.$console.log('=======bbjjdjdd',this.flowExtInfo)
      if(this.isFlowFrom && row.flowExtData){
        for(var key in row.flowExtData){
          row.flowExtData[key] = row[key];
        }
      }
      this.reqParams.singleBody = row;
      this.commonData = reqCommonMsg(this.reqParams)
      updateGeneralFlowInfo(this.commonData).then(() => {
        done();
        this.singleBody={}
        this.onLoad(this.page);
        this.$message({
          customClass:'zZindex',
          type: 'success',
          message: '操作成功!'
        });
      }, error => {
        //this.$console.log(error);
        loading();
      });
      //this.$console.log('loading = ',loading)
    },
    /**
     * 删除一条记录
     */
    rowDel(row) {
      this.$confirm('确定将选择数据删除?', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          this.reqParams.singleBody = row;
          this.commonData = reqCommonMsg(this.reqParams);
          return deleteGeneralFlowInfo(this.commonData);
        })
        .then(() => {
          this.onLoad(this.page);
          this.$message({
            customClass:'zZindex',
            type: 'success',
            message: '操作成功!'
          });
        }).catch(() => {});
    },

    /**
     * 双击打开详细窗口
     */
    handleRowDBLClick (row, event) {
      if(this.permission.general_flow_info_dbclick){
        this.$refs.crud.rowView(row,row.$index);
      }
    },
    
    /**
     * 搜索重置
     */
    searchReset() {
      this.conditions =[];
      this.singleBody = {};
      this.onLoad(this.page);
    },

    /**
     * 搜索
     */
    searchChange(params, done) {
      this.singleBody = params
      this.page.currentPage = 1;
      this.onLoad(this.page);
      done();
    },
    refreshChange(){
      this.onLoad(this.page);
    },
    selectionChange(list) {
      this.selectionList = list;
    },
    selectionClear() {
      this.selectionList = [];
      this.$refs.crud.toggleSelection();
    },
    /**
     * 处理批量删除
     */
    handleDelete() {
      if (this.selectionList.length === 0) {
        this.$message.warning('请选择至少一条数据');
        return;
      }
      this.$confirm('确定将选择数据删除?', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          this.reqParams.listBody = this.ids;
          this.commonData = reqCommonMsg(this.reqParams);
          return deleteGeneralFlowInfoList(this.commonData);
        })
        .then(() => {
          this.onLoad(this.page);
          this.$message({
            customClass:'zZindex',
            type: 'success',
            message: '操作成功!'
          });
          this.$refs.crud.toggleSelection();
        }).catch(() => {});
    },
    /**
     * 拷贝记录
     */
    handleCopy(row){
      this.$confirm('确定复制数据?', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.loading=true;
        let copyValue=row;
        copyValue.id='0';
        copyValue.dataSign='0'
        copyValue.tableName='拷贝 '+ copyValue.tableName; 
        this.reqParams.singleBody = copyValue;
        this.commonData = reqCommonMsg(this.reqParams)
        saveSysToolTables(this.commonData).then(() => {
          this.singleBody={};
          this.onLoad(this.page);
          this.$message({
            customClass:'zZindex',
            type: 'success',
            message: '操作成功!'
          });
          this.loading=false;
        }, error => {
          //this.$console.log(error);
          this.loading=false;
        });
      }).catch(() => {});       
    },
    /**
     * 打开编辑、查询弹窗前查询记录
     */
    beforeOpen(done, type) {
      this.findObject(this.option.column, 'tableList').dicData = this.tableList;
      this.operateType = type;
      //如果用了流程 需要做表单切换
      // if(this.isFlowFrom){
      //   this.option = this.deepClone(this.optionTmp);
      // }
      if (['edit', 'view'].includes(type)) {
        this.reqParams =  {
          singleBody: {
            id:this.form.id
          }
        }
        let commonData = reqCommonMsg(this.reqParams)
        const loading = this.$loading({
          lock: true,
          text: 'Loading',
          spinner: 'el-icon-loading'
        });
        queryGeneralFlowInfo(commonData).then(res => {
          this.testForm();
          this.form = res.data.body.singleBody;
          this.form.tableList =  JSON.parse(this.form.tableList);
          if(this.form.flowExtData){
            this.testForm(done);
            for(var key in this.form.flowExtData){
              this.form[key] = this.form.flowExtData[key]; 
            } 
          }
          loading.close();
          done();
        }, error => {
          //this.$console.log(error);
          loading.close();
        });
      }
      else
      {
        done();
      }
    },
    /**
     * 测试动态添加表单
     */
    testForm(){
      //this.$console.log('test==')
    },
    
    /**
     * 翻页查询
     */
    currentChange(currentPage) {
      this.page.currentPage = currentPage;
    },

    /**
     * 更改每页条数
     */
    sizeChange(pageSize) {
      this.page.pageSize = pageSize;
    },
    /**
     * 自定义查询条件
     */
    filterChange(result) {
      this.page.currentPage = 1;
      this.conditions = filterFormat(result)
      this.onLoad(this.page);
    },
    /**
     * 列表排序
     */
    sortChange(val){
      this.orderRules=val
      this.onLoad(this.page);
    },
  
    /**
     * 导出Excel
     */
    exportExcel() {
      this.reqParams =  {
        singleBody: this.singleBody,
        listBody: [{}],
        sqlCondition: this.conditions,
        orderRule: this.orderRules,
        currentPage:1, 
        pageSize: 100
      }
      //this.$console.log('reqParams = ',this.reqParams)
      this.commonData = reqCommonMsg(this.reqParams)
      exportGeneralFlowInfoExcel(this.commonData);
    },
    /**
     * 获取业务字典参数
     */
    async getBizDict() {
      // let dicData = await this.$params.getBizDict('["bizType"]');
      // //console.log('dicData.bizType===',dicData.bizType);
      // this.findObject(this.option.column, 'bizType').dicData = dicData.bizType;
      //如果用了流程 需要做表单切换,此处将赋值好字典的表单做备份
      if(this.isFlowFrom){
        this.optionTmp = this.deepClone(this.option);
      }
    },
    /**
     * 获取系统字典表
     */
    async getSysDict() {
      let dicData = await this.$params.getSysDict('["roleType"]')
      this.findObject(this.option.column, 'roleType').dicData = dicData.roleType
      this.findObject(this.option.column, 'tableList').dicData = this.tableList;
      this.findObject(this.option.column, 'approveTreeNo').dicData = this.treeList;
      
      //如果用了流程 需要做表单切换,此处将赋值好字典的表单做备份
      if(this.isFlowFrom){
        this.optionTmp = this.deepClone(this.option);
      }
    }
    ,
    /**
     * 获取业务表名字
     * */
    async loadTableName() {
      this.tableList =[];
      this.reqParams =  {
        singleBody: {
          tableType: 'biz'
        },
        listBody: [{}],
        currentPage: 1, 
        pageSize: 999
      }
      this.commonData = reqCommonMsg(this.reqParams)
      await querySysToolTablesListPage(this.commonData).then(res => { 
        const data = res.data.body.listBody;
        data.forEach((item, index) => {
          this.tableList.push({
            label: item.tableComment,
            value: item.tableName
          });
        });
        setTimeout(() => {
          this.getBizDict();
          this.getSysDict();
        }, 2000);
      }, error => {
      }); 
    },
    /**
     * 获取机构树
     */
    getTree(){
      let getOrgTimer = setInterval(() => {
        this.treeList = [];
        if(this.genOrgTree){
          this.treeData = [];
          this.genOrgTree.forEach(element => {
            if(element.parentOrgNo == this.website.orgNo.genTreeOrgNo && element.orgType == '3'){
              this.treeList.push({
                label: element.orgName,
                value: element.orgNo
              })
            }
          });
          clearInterval(getOrgTimer);
        }
      }, 100);
    }
  },
  created() {
    this.showColumn = this.$getStore({name:  this.userInfo.userId +'generalFlowInfoColumn'});
    //获取机构树
    this.getTree();
    //获取业务字典
    this.loadTableName();
  },
  watch: {
    showColumn: {
      handler(newValue, oldValue) {
        this.$setStore({name:  this.userInfo.userId+'generalFlowInfoColumn', content: this.showColumn});
      },
      deep: true
      //this.$setStore({name: this.userInfo.userId +'generalFlowInfoColumn', content: this.showColumn});
    }
  }
};
</script>
<style>
.process .el-collapse-item__arrow {
  margin-top: 0px !important;
}
</style>
